const chromeMng = require('../mng/chromeMng.20180824'),
  log = require('../util/log'),
  formatDate = require('../../lib/formatDate')

var date = ''

exports.start = () => {
  if (date == formatDate(new Date()).substring(0, 10)) {
    return
  }
  date = formatDate(new Date()).substring(0, 10)
  if (!chromeMng.client) {
    return
  }
  if (!mongoMng.db) {
    return
  }
  const mongoMng = require('../mng/mongoMng')
  if (chromeMng.busy) {
    return
  }
  chromeMng.busy = true
  chromeMng.getTaobaoKeyWords().then(keyWords => {
    chromeMng.busy = false
    keyWords.forEach(q => {
      getTaobaoItems(q)
    })
  })
}

function getTaobaoItems(q) {
  if (chromeMng.busy) {
    setTimeout(() => {
      getTaobaoItems(q)
    }, 1000)
    return
  }
  chromeMng.busy = true
  chromeMng.getTaobaoItems({
    q: q
  }).then(items => {
    chromeMng.busy = false
    items.forEach(item => {
      getTaobaoAdvLink(item.link)
    })
  })
}

function getTaobaoAdvLink(link) {
  const mongoMng = require('../mng/mongoMng')
  mongoMng.db.collection('item').find({
    link: link
  }).toArray((err, result) => {
    if (err) {
      log(err);
      return;
    }
    if (result.length > 0) {
      return
    }
    if (chromeMng.busy) {
      setTimeout(() => {
        getTaobaoAdvLink(link)
      }, 1000)
      return
    }
    chromeMng.busy = true
    chromeMng.getTaobaoAdvLink({
      link: link
    }).then(result => {
      chromeMng.busy = false
      log(link, result)
      mongoMng.db.collection('item').insert({
        link: link,
        advLink: result
      }, (err, result) => {
        if (err) {
          log(err);
          return;
        }
      });
    }, result => {
      chromeMng.busy = false
      log(result)
    })
  })
}
